package it.unipr.ce.dsg.s2p.example.peerdroid;



import static npu.database.Constant.KEY_ROWID;
import static npu.database.Constant.KEY_GIVENNAME;
import static npu.database.Constant.KEY_PHONE;
import static npu.database.Constant.KEY_EMAIL;


import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import android.view.ContextMenu;  
import android.view.MenuItem;  
import android.view.View;  
import android.view.ContextMenu.ContextMenuInfo;  
import android.widget.AdapterView;

import npu.database.SQLiteAdapter;
import npu.database.SingleData;


public class View_contact extends Activity{
     listviewAdapter adapter;
     ListView ltvDisplay;
     private SQLiteAdapter mySQLiteAdapter;
     
      private ArrayList<HashMap<String,String>> list;
      
     @Override
         public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
        //call xml
          setContentView(R.layout.view_contact);
          mySQLiteAdapter = new SQLiteAdapter(this);
        //handle listview
          ltvDisplay = (ListView)findViewById(R.id.ltvViewContact);
          //if datalist is not empty then update it to database, at version 2: need to auto
          // update right after receive new message.
         if(PeerActivity.peer.CheckDataListEmpty()){// ifdatlist is empty then display databse
        	 //otherwise check new income data, compare with current datbase, update then display
        	 loadtolistview(); //store date into list
             adapter = new listviewAdapter(this, list);
             adapter.notifyDataSetChanged();//delete
             ltvDisplay.setAdapter(adapter);
         }else{
          UpdateDatabase();
          loadtolistview(); //store date into list
          adapter = new listviewAdapter(this, list);
          adapter.notifyDataSetChanged();//delete
          ltvDisplay.setAdapter(adapter);
         }
          
          
          //create contextmenu for listview
          registerForContextMenu(ltvDisplay); 

     }   //end onCreate
     
     /**check new phone number, if it is not in database --> insert, otherwise update,
      * then empty datalist
      */
       private void UpdateDatabase(){
    	   //
    	   int same = 0;
    	   int newdata =0;
    	   if(PeerActivity.peer.CheckDataListEmpty()){
    		   Toast.makeText(this,"There is no update contact!", Toast.LENGTH_LONG).show();
    	   }
    	   else{//check new phone number
    		   
//    		   ArrayList<String> phonelist = new ArrayList<String>();
//    		   phonelist.addAll(PeerActivity.peer.getListPhone());
    		   
    		   ArrayList<SingleData> newdatalist = new ArrayList<SingleData>();
    		   newdatalist.addAll(PeerActivity.peer.getDataList());
    		   
    		   int c = PeerActivity.peer.getsizedata();
    		 
    		  
    		   for(int i=0;i<c; i++){//traversal to each, check 
    			   mySQLiteAdapter.openToRead();
    			   Cursor cursor = mySQLiteAdapter.checkphone(newdatalist.get(i).getPhone());
   				   startManagingCursor(cursor);
   				if (!cursor.isAfterLast()) //if has same phone # then update
				{
					same++; //count number similar phone number update
        	
					do
					{	 mySQLiteAdapter.openToWrite();
						//remain the other, because get from interface
						mySQLiteAdapter.updatephonenumber(newdatalist.get(i));
               
					}
					while (cursor.moveToNext());
					cursor.close();// let java know that you are through with the cursor.
					mySQLiteAdapter.close();
				}
				else{
        
					newdata++;
					//insert if new data
					mySQLiteAdapter.openToWrite();
					mySQLiteAdapter.insert(newdatalist.get(i));
        
					mySQLiteAdapter.close();  
        
				}//end else
   				   
   				   
    		   }//end for
    	   }
    	   //empty datalist
    	   mySQLiteAdapter.close();
    	   PeerActivity.peer.ClearDataList();
    	   Toast.makeText(this,"You have: " + same+ " update and " + newdata
    			   + " data", Toast.LENGTH_LONG).show();
    	   
       }
       private void loadtolistview() { 
          
//          mySQLiteAdapter = new SQLiteAdapter(this);
          mySQLiteAdapter.openToRead();

          Cursor cursor = mySQLiteAdapter.queueAll();
          startManagingCursor(cursor);
         
          
          cursor.moveToFirst();
          list = new ArrayList<HashMap<String,String>>(); 
          if (!cursor.isAfterLast())
          {
              do
              {
                 Long lObj = new Long(cursor.getString(cursor.getColumnIndexOrThrow(mySQLiteAdapter.KEY_ROWID)));
                 String str = lObj.toString();//convert long to string
                 String name = cursor.getString(cursor.getColumnIndexOrThrow(mySQLiteAdapter.KEY_GIVENNAME)) 
                		 + " " + cursor.getString(cursor.getColumnIndexOrThrow(mySQLiteAdapter.KEY_FAMILYNAME)) ;
                 HashMap<String,String> temp = new  HashMap<String,String>();
   
                  temp.put(KEY_ROWID, str);   //row ID 
                  temp.put(KEY_GIVENNAME, name);  //name = first + last 
                  temp.put(KEY_PHONE,  cursor.getString(cursor.getColumnIndexOrThrow(mySQLiteAdapter.KEY_PHONE))); 
                  temp.put(KEY_EMAIL,  cursor.getString(cursor.getColumnIndexOrThrow(mySQLiteAdapter.KEY_EMAIL)));
                 
                  list.add(temp);
                 
              }
              while (cursor.moveToNext());
                      
          }
          
          // let java know that you are through with the cursor.
          cursor.close();
          mySQLiteAdapter.close();

    }//end  loadtolistview()
       
       //create context menu
         @Override  
         public void onCreateContextMenu(ContextMenu menu, View  v,ContextMenuInfo  menuInfo) {  
         super.onCreateContextMenu(menu, v, menuInfo);  
       
         if (v.getId()==R.id.ltvViewContact) {
               AdapterView.AdapterContextMenuInfo info =  (AdapterView.AdapterContextMenuInfo)menuInfo;

//             menu.setHeaderTitle("Edit contact");
              menu.setHeaderTitle("Edit  "+(String)list.get(info.position).get(KEY_GIVENNAME));//put name of  current select into  Title
               menu.add(0, v.getId(), 0, "Edit");  
                 menu.add(0, v.getId(), 0, "Delete");
                 menu.add(0, v.getId(), 0, "Cancel");

           }

     
         } 
  
         //handle action with each select on context menu
         @Override  
         public boolean onContextItemSelected(MenuItem item) {  
           AdapterView.AdapterContextMenuInfo info =  (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
           HashMap<String,String> hst = new  HashMap<String,String>();
               hst=list.get(info.position);
           
         //           int count = list.size();
           String id = (String)hst.get(KEY_ROWID);
           String name = (String)hst.get(KEY_GIVENNAME);
             if(item.getTitle()=="Edit"){
               EditItem(item.getItemId());
               
               }  
             else if(item.getTitle()=="Delete"){ DeleteItem(name,id);}  
             else {return false;}  
         return true;  
         } // end onContextItemSelected
         
         public void DeleteItem(String str,String id){
          //toast name of
          Toast.makeText(this, "You  Delete " + str + " "+ id,  Toast.LENGTH_LONG)
            .show();
          mySQLiteAdapter.openToRead();
          mySQLiteAdapter.deleteRow( Long.parseLong(id));
          mySQLiteAdapter.close();  
          
          //update listview
           loadtolistview(); //store date into list
               adapter = new listviewAdapter(this, list);
               adapter.notifyDataSetChanged();//delete
               ltvDisplay.setAdapter(adapter);     
         }
         
         public void EditItem(int id){
          //toast name of 
          Toast.makeText(this, "You  selected Edit " ,  Toast.LENGTH_LONG)
            .show();
         }
      
         
         
         @Override
     	protected void onDestroy() {
     	super.onDestroy();
     	if(mySQLiteAdapter != null)mySQLiteAdapter.close();
     	}    
         
         
}//end class


